#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <string>
#include "Fail.hpp"

using namespace std;

class tcp_client
{
public:
    //默认构造
    tcp_client(string ip, uint16_t port)
        : _ip(ip)
        , _port(port)
    {}

    //初始化
    void init()
    {
        //创建套接字
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if(_sock < 0)
        {
            perror("create sock fail");
            exit(SOCKET_FAIL);
        }
    }

    //启动
    void start()
    {
        //服务方结构体
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = inet_addr(_ip.c_str());

        int cnt = 5;
        
        //建立连接
        while(connect(_sock, (struct sockaddr*)&server, sizeof(server)) && cnt > 0)
        {   
            sleep(1);
            cout << "正在尝试重新连接, 剩于重连次数:" << cnt-- << endl;
        }
        if(cnt <= 0)
        {
            perror("connect fail");
            exit(CONNECT_FAIL);
        }

        //连接成功，进行通信
        char buff[1024];
        while(true)
        {   
            string message;
            cout << "please enter>";
            getline(cin, message);

            write(_sock, message.c_str(), message.size());

            ssize_t n = read(_sock, buff, sizeof(buff) - 1);
            if(n > 0)
            {
                buff[n] = '\0';
                cout << "server echo> " << buff << endl;
            }
            else if(n == 0)
            {
                cerr << "server quit" << endl;
                break;
            }
            else
            {
                perror("read fail");
                break;
            }
        }
    }

    //析构函数
    ~tcp_client()
    {}

private:
    string _ip; //服务器ip
    int _port; //服务器端口号
    int _sock;
};
